'''
Created on Apr 20, 2012

@author: root
'''
from Node import Node
import urlgrabber
import threading
import Queue
import ssh
from Log_Java import Log_Java



class Java:
    
    Nodes = []
    Log = []
    Users = []
    returnQueue = Queue.Queue()
    openJDKStatus = []
    JDKStatus = []
#    localJavaBin = "/tmp"
#    remoteJavaBin = "/tmp"

    def sshCopy(self,node, localFile,remoteFile,callingModule):
        try:
            sshCon = ssh.Connection(node.get_hostName(), username=self.installUser, password=self.installPW)
           
            #Check on send a return status back.  SSH doesn't yet
           
            sshCon.put(localFile,remoteFile)
            execStatus = 0
            execReturn = "Copy Successful"
        except Exception, err:
            exception = "ERROR: Trouble with SSH Connection to "+node.get_hostName()+" : "+str(err)
            execReturn = exception
            execStatus = 1
            #self.fsLog.exception(exception)
        log_Java = Log_Java()
        log_Java.add(node.get_hostName(),callingModule,"SSHCopy" ,execReturn,execStatus)
        self.Log.add_Log_Java(log_Java) 
        self.returnQueue.put((node.get_hostName(),execStatus,execReturn))





    def sshExec(self,cmd,node,callingModule):
        try:
            sshCon = ssh.Connection(node.get_hostName(), username=self.installUser, password=self.installPW)
            (execStatus,execReturn) = sshCon.executeSt(cmd)
        except Exception, err:
            exception = "ERROR: Trouble with SSH Connection to "+node.get_hostName()+" : "+str(err)
            execReturn = exception
            execStatus = 1
            #self.fsLog.exception(exception)
        
        log_Java = Log_Java()
        log_Java.add(node.get_hostName(),callingModule,"SSHExec" ,execReturn,execStatus)
        self.Log.add_Log_Java(log_Java) 
        self.returnQueue.put((node.get_hostName(),execStatus,execReturn))




    # DOES NOT WORK
    def download(self):
        url = "http://download.oracle.com/otn-pub/java/jdk/7u4-b20/jdk-7u4-linux-x64.rpm?AuthParam=1335803005_6a3af21f5d933b6aea9728ccda063bee"
        javaFile = "/tmp/jdk-7u4-linux-x64.rpm"
        localFile = urlgrabber.urlgrab(url,filename=javaFile)
        
    def installJDK(self,localJavaBin):
        threadCount = 0
        Threads = [] 
        installCMD = "sudo rpm -ivh --nodeps "+ localJavaBin
        for node in self.Nodes:
            Threads.append(threading.Thread(target=self.sshExec,args=(installCMD,node,"Java:Install")))
            Threads[threadCount].daemon=True
            Threads[threadCount].start()     
            threadCount = threadCount + 1
        for thread in Threads:
            thread.join()
            (hostName,status,results) = self.returnQueue.get()
           
        
        
        
    def checkJDK(self):
        print "Check Open JDK"
        threadCount = 0
        Threads = [] 
        checkCurrentCMD = "sudo rpm -qa | grep jdk"
        for node in self.Nodes:
            Threads.append(threading.Thread(target=self.sshExec,args=(checkCurrentCMD,node,"Java:CheckJDK")))
            Threads[threadCount].daemon=True
            Threads[threadCount].start()     
            threadCount = threadCount + 1
        for thread in Threads:
            thread.join()
            (hostName,status,results) = self.returnQueue.get()
            if results:
                if ('openjdk' in results[0]):
                    print "openJDK found.  Oracle/Sun JDK Recommended"
                    self.openJDKStatus.append((hostName,results[0][:-1]))
                elif str(results[0]).startswith('jdk') and ('openjdk' not in results[0]):
                    print "Oracle Sun JDK Installed : "+str(results[0])
                    self.JDKStatus.append((hostName,results[0][:-1]))              
                    print self.JDKStatus
      # Based on return Report java Status and install
      # Perhaps accept a flag if openjdk is acceptable
      
    def pushJDK(self,localJavaBin,remoteJavaBin):
        print "Push JDK"
        threadCount = 0
        Threads = [] 
        for node in self.Nodes:
            Threads.append(threading.Thread(target=self.sshCopy,args=(node,localJavaBin,remoteJavaBin,"Java:pushJDK")))
            Threads[threadCount].daemon=True
            Threads[threadCount].start()     
            threadCount = threadCount + 1
        for thread in Threads:
            thread.join()
            (hostName,status,results) = self.returnQueue.get()
          
    
                
    def removeOpenJDK(self):
        print "Remove OpenJDK"
        threadCount = 0
        Threads = [] 
        checkCurrentCMD = "rpm -e "
        for node in self.openJDKStatus:
            removeCMD = "sudo rpm -e --nodeps "+ node[1]
            nodeObj = Node(node[0],"","")
            Threads.append(threading.Thread(target=self.sshExec,args=(removeCMD,nodeObj,"Java:Remove")))
            Threads[threadCount].daemon=True
            Threads[threadCount].start()     
            threadCount = threadCount + 1
        for thread in Threads:
            thread.join()
            (hostName,status,results) = self.returnQueue.get()
          
                
    def set_Users(self):
        for user in self.Users:
            if user.get_role() == "r":
                self.installUser = user.get_userName()
                self.installPW = user.get_password()
            elif user.get_role() == "m":
                self.mapredUser = user.get_userName()
                self.mapredPW = user.get_password()
            elif user.get_role() == "h":
                self.hdfsUser = user.get_userName()
                self.hdfsPW = user.get_password()           

    def __init__(self,Log,Nodes,Users):
        print "Java Install Module"
        self.Log = Log
        self.Users = Users
        self.Nodes = Nodes
        self.set_Users()
        #self.localJavaBin = localJavaBin
        #self.remoteJavaBin = remoteJavaBin

